package kycadminrepo

import (
	"context"
	"fmt"

	"git.bybit.com/svc/dbstructure_user/pkg/o_member_kyc_decision"
	"git.bybit.com/svc/go/pkg/bdal/bqb"
	"git.bybit.com/svc/go/pkg/bzap"
	jsoniter "github.com/json-iterator/go"
	"go.uber.org/zap"
)

// GetProviderDecision Get decision from o_member_kyc_decision by provider
func (r *repo) GetProviderDecision(ctx context.Context, provider int8) ([]*o_member_kyc_decision.Record, error) {
	var records []*o_member_kyc_decision.Record

	pool, err := r.kycDB.DBDefaultReplicaNodePool(ctx)
	if err != nil {
		bzap.LogError(r.logger.With(zap.Int8("provider", provider)), "GetProviderDecision DB error", err)

		return nil, err
	}

	dcsSQL := o_member_kyc_decision.Select().WhereC(func(wb *bqb.WhereBuilder) {
		o_member_kyc_decision.FldProvider.EQ(wb)
	}).OrderByC(o_member_kyc_decision.FldId, bqb.ASC).SQL()

	records, err = o_member_kyc_decision.ScanRecords(dcsSQL.QueryArgs(ctx, pool, bqb.Args{
		o_member_kyc_decision.FldProvider.Param(): provider,
	}))
	if err != nil {
		return nil, err
	}

	return records, nil
}

func (r *repo) GetAllDecisions(ctx context.Context) ([]*o_member_kyc_decision.Record, error) {
	var records []*o_member_kyc_decision.Record
	pool, err := r.kycDB.DBDefaultReplicaNodePool(ctx)
	if err != nil {
		bzap.LogError(r.logger, "GetAllDecisions DB error", err)

		return nil, err
	}

	dcsSQL := o_member_kyc_decision.Select().SQL()
	records, err = o_member_kyc_decision.ScanRecords(dcsSQL.QueryArgs(ctx, pool, bqb.Args{}))
	if err != nil {
		return nil, err
	}

	return records, nil
}

type DecisionComments struct {
	En string `json:"en"`
}

func (r *repo) GetProviderDecisionMaps(ctx context.Context, provider int8) (map[string]string, error) {
	records, err := r.GetProviderDecision(ctx, provider)
	if err != nil {
		return nil, err
	}
	decisionMaps := make(map[string]string)
	for _, record := range records {
		if record.DecisionComments.Valid {
			cmt := &DecisionComments{}
			err = jsoniter.UnmarshalFromString(record.DecisionComments.String, cmt)
			if err != nil {
				continue
			}

			decisionMaps[record.DetailsLabel] = cmt.En
		}
	}

	return decisionMaps, nil
}

// GetAllDecisionMaps Get all decision maps
func (r *repo) GetAllDecisionMaps(ctx context.Context) (map[string]string, error) {
	records, err := r.GetAllDecisions(ctx)
	if err != nil {
		return nil, err
	}
	allDecisionMaps := make(map[string]string)
	for _, record := range records {
		if !record.DecisionComments.Valid {
			continue
		}
		cmt := &DecisionComments{}
		err = jsoniter.UnmarshalFromString(record.DecisionComments.String, cmt)
		if err != nil {
			continue
		}
		k := fmt.Sprintf("%d-%s", record.Provider, record.DetailsLabel)
		allDecisionMaps[k] = cmt.En
	}

	return allDecisionMaps, nil
}
